/**
 * @Author: whflovecn
 * @Date: 2021-04-19 10:57:32
 * @LastEditTime: 2021-05-31 17:09:33
 * @LastEditors: whflovecn
 * @Description: 
 * @FilePath: \complex\app\extend\context.js
 */
"use strict";

module.exports = {
  whereStr(where) {
    let whereList = [];
    for (let key in where) {
      if (Array.isArray(where[key])) {
        if (where[key].length == 2) {
          if (
            isNaN(where[key][0]) &&
            !isNaN(Date.parse(where[key][0])) &&
            isNaN(where[key][1]) &&
            !isNaN(Date.parse(where[key][1]))
          ) {
            //date between
            whereList.push(
              `${key} between '${where[key][0]}' and '${where[key][1]}'`
            );
          } else {
            //in
            whereList.push(`${key} in ('${where[key].join("','")}')`);
          }
        }
      } else if (typeof where[key]=='string') {
        //like
        if (where[key].indexOf("%") >= 0){
          whereList.push(`${key} like '${where[key]}'`);
        }else{
          whereList.push(`${key} = '${where[key]}'`);
        }
      } else {
        // =
        whereList.push(`${key} = '${where[key]}'`);
      }
    }
    return `${whereList.length > 0 ? "where " + whereList.join(" and ") : ""}`;
  },
  generateSql(sqlStr, body) {
    let params = {...body}
    let sql = sqlStr;
    for (let key in body) {
      if(sql.indexOf(`@${key}@`)>=0){
        delete params[key]
      }
      let reg = new RegExp("@" + key + "@", "g");
      sql = sql.replace(reg, body[key]);
    }
    return {"sqlStr":sql,params};
  },
  ordersArr(orders) {
    let ordersList = [];
    for (let i = 0; i < orders.length; i++) {
      ordersList.push(
        orders[i].length > 1
          ? `${orders[i][0]} ${orders[i][1]}`
          : `${orders[i][0]} asc`
      );
    }
    return ordersList;
  },
  getColumnsArr(obj, arr,role) {
    let cols = [];
    if (typeof obj == "undefined") {
      cols = arr;
    }
    let colList = [];
    if (
      obj != "*" &&
      typeof obj != "undefined"
    ) {
      if (!ctx.app.isJSON(obj)) {
        cols = obj.split(",");
      } else {
        cols = JSON.parse(obj);
      }
      for (let i = 0; i < cols.length; i++) {
        const arr = cols[i].split(".");
        if (arr.indexOf(arr) >= 0) {
          colList.push(cols[i]);
        }
      }
    }
    if ( //如果是管理员则允许查询所有字段
      obj == "*" ||
      role.indexOf("ADMIN") >= 0
    ) {
      colList = ["*"];
    }
    return colList;
  },
};
